package com.ruoyi.business.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.domain.TOrderInfo;
import com.ruoyi.business.domain.TRecipientInfo;
import com.ruoyi.business.response.ResponseData;
import com.ruoyi.business.service.BasePayment;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.BaiduApiUtil;
import com.ruoyi.common.utils.HttpResponse;
import com.ruoyi.common.utils.HttpUtils;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

@Service("hdfPayService")
public class HdfPayServiceImpl extends BasePayment{
    @Override
    public JSONObject createPayOrder(TOrderInfo orderInfo) throws Exception {
        JSONObject jsonObject = new JSONObject();
        TRecipientInfo userRecipientInfo = userRecipientService.selectTRecipientInfoById(orderInfo.getRecipientId());
        HashMap<String, String> headerMap = new HashMap();
        HashMap<String, String> dataMap = new HashMap();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String cookieStr = userRecipientInfo.getCookie();
        JSONObject cookieObj = JSONObject.parseObject(cookieStr);
        logger.info("挂码省份：" + userRecipientInfo.getProvince());
        logger.info("挂码城市：" + userRecipientInfo.getCity());
//        JSONObject ipObject = commonService.getPoxyIp(orderInfo);
        Map location = BaiduApiUtil.getCoordinate(userRecipientInfo.getProvince()+userRecipientInfo.getCity());
//        String ip = ipObject.getString("ip");
//        String port = ipObject.getString("port");
        headerMap.put("User-Agent","Nebula AlipayDefined(nt:WIFI,ws:360|0|3.0) AliApp(AP/10.0.18.062203) AlipayClient/10.0.18.062203 Language/zh-Hans useStatusBar/true");
        String url ="https://api.haoduo.fun/pay/scanPay/codeNotify?auth_code="+orderInfo.getAliAuthCode()+"&qrCodeId="+cookieObj.getString("qrCodeId")+"&amount=&orderType=1&urlType=1&app_id=2021001125693893";
        logger.info("收银台HTMLurl："+url);

        HttpResponse httpResponse = HttpUtils.httpFormGet(url,headerMap,"","HDF","");
        logger.info("返回的HTML:"+httpResponse.getDocument().text());

        Elements priceElements =  httpResponse.getDocument().select("p[id=mchId]");
        Element element1 = priceElements.get(0);
        String mchId = element1.text();
        cookieObj.put("mchId",mchId);
        priceElements =  httpResponse.getDocument().select("p[id=userId]");
        element1 = priceElements.get(0);
        String userId = element1.text();

        priceElements =  httpResponse.getDocument().select("p[id=sign]");
        element1 = priceElements.get(0);
        String sign = element1.text();

        priceElements =  httpResponse.getDocument().select("p[id=mchName]");
        element1 = priceElements.get(0);
        String mchName = element1.text();
        cookieObj.put("mchName",mchName);
        priceElements =  httpResponse.getDocument().select("p[id=outTradeNo]");
        element1 = priceElements.get(0);
        String outTradeNo = element1.text();
        priceElements =  httpResponse.getDocument().select("p[id=body]");
        element1 = priceElements.get(0);
        String body = element1.text();
        cookieObj.put("body",body);

        priceElements =  httpResponse.getDocument().select("p[id=client]");
        element1 = priceElements.get(0);
        String client = element1.text();
        cookieObj.put("client",client);

        priceElements =  httpResponse.getDocument().select("p[id=userName]");
        element1 = priceElements.get(0);
        String userName = element1.text();
        priceElements =  httpResponse.getDocument().select("p[id=payType]");
        element1 = priceElements.get(0);
        String payType = element1.text();
        priceElements =  httpResponse.getDocument().select("p[id=openID]");
        element1 = priceElements.get(0);
        String openID = element1.text();
        cookieObj.put("openID",openID);

        priceElements =  httpResponse.getDocument().select("p[id=subOpenID]");
        element1 = priceElements.get(0);
        String subOpenID = element1.text();
        priceElements =  httpResponse.getDocument().select("p[id=pierce]");
        element1 = priceElements.get(0);
        String pierce = element1.text();
        cookieObj.put("pierce",pierce);

        priceElements =  httpResponse.getDocument().select("p[id=appId]");
        element1 = priceElements.get(0);
        String appId = element1.text();

        dataMap = new HashMap();
        dataMap.put("mchId",mchId);
        dataMap.put("userId",userId);
        dataMap.put("mchName",mchName);
        dataMap.put("outTradeNo",outTradeNo);
        dataMap.put("body",body);
        dataMap.put("client",client);
        dataMap.put("userName",userName);
        dataMap.put("payType",payType);
        dataMap.put("openID",openID);
        dataMap.put("subOpenID",subOpenID);

        dataMap.put("pierce",pierce);
        dataMap.put("openid",orderInfo.getAliUserId());
        dataMap.put("type","1");
        dataMap.put("qrCodeId",cookieObj.getString("qrCodeId"));
        dataMap.put("latitude",location.get("lat").toString());
        dataMap.put("longitude",location.get("lng").toString());
        dataMap.put("amount",orderInfo.getMoney()+"");
//        userRecipientInfo.setCookie(cookieObj.toJSONString());
//        userRecipientService.update(userRecipientInfo);
        url = "https://api.haoduo.fun/pay/scanPay/realPay";
        logger.info("下单URL："+url);
        StringBuilder buf = new StringBuilder("");
        HttpUtils.buildPayParams(buf, dataMap);
        String preStr = buf.toString();
        logger.info("请求参数："+preStr);

//        headerMap.put("Referer","https://www.shouyinbei.net/wap/merchant/h5pay?auth_code="+orderInfo.getAliAuthCode()+"&userAppId="+qrcode_);

        String payHttpResponse = HttpUtils.sendPostRequest(url,preStr,headerMap);

        logger.info("好多分请求返回的:"+payHttpResponse);

        JSONObject payInforesultObj = JSONObject.parseObject(payHttpResponse);
        if(payInforesultObj.getIntValue("code")!=200){
            jsonObject.put("code","100");
            jsonObject.put("msg","获取连接失败");
            logger.info("========HDF修改收款账号为不可用===============");
            userRecipientInfo.setChannelDisabled(1);
            userRecipientInfo.setDisabledInfo(payInforesultObj.getString("msg"));
            userRecipientService.updateTRecipientInfo(userRecipientInfo);
            return jsonObject;
        }
        JSONObject jspay_info = payInforesultObj.getJSONObject("data");
        String tradeNO = jspay_info.getString("data");
//        JSONObject payInfoObj = new JSONObject();
//        payInfoObj.put("appid",payInforesultObj.getString("appid"));
//        payInfoObj.put("merchant_id",payInforesultObj.getString("merchant_id"));
//        payInfoObj.put("qrcode",qrcode_);
//        payInfoObj.put("order_id",payInforesultObj.getString("order_id"));
//        payInfoObj.put("notify_key",payInforesultObj.getString("notify_key"));
//        payInfoObj.put("third_order_id",payInforesultObj.getString("third_order_id"));
//        orderInfo.setQrcodeTxt(payInfoObj.toJSONString());
//        orderInfoDao.update(orderInfo);

        jsonObject.put("payUrl",tradeNO);
        jsonObject.put("orderNo",jspay_info.getString("orderNo"));
        jsonObject.put("code","200");
        return jsonObject;
    }


    public JSONObject createWxPayOrder(TOrderInfo orderInfo) throws ServiceException, UnsupportedEncodingException {
        JSONObject jsonObject = new JSONObject();
        TRecipientInfo userRecipientInfo = userRecipientService.selectTRecipientInfoById(orderInfo.getRecipientId());
        HashMap<String, String> headerMap = new HashMap();
        HashMap<String, String> dataMap = new HashMap();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String cookieStr = userRecipientInfo.getCookie();
        JSONObject cookieObj = JSONObject.parseObject(cookieStr);
        logger.info("挂码省份：" + userRecipientInfo.getProvince());
        logger.info("挂码城市：" + userRecipientInfo.getCity());
        JSONObject ipObject = commonService.getPoxyIp(orderInfo);
        String ip = ipObject.getString("ip");
        String port = ipObject.getString("port");
        headerMap.put("User-Agent","Mozilla/5.0 (iPhone; CPU iPhone OS 15_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.23(0x18001723) NetType/WIFI Language/zh_CN");

        String url ="https://api.haoduo.fun/pay/scanPay/codeNotify?qrCodeId="+cookieObj.getString("qrCodeId")+"&amount=&orderType=1&urlType=1";
        logger.info("收银台HTMLurl："+url);

        HttpResponse httpResponse = HttpUtils.httpFormGet(url,headerMap,"","HDF","");
        logger.info("返回的HTML:"+httpResponse.getDocument().text());

        Elements priceElements =  httpResponse.getDocument().select("p[id=mchId]");
        Element element1 = priceElements.get(0);
        String mchId = element1.text();
        logger.info("mchId:"+mchId);
        priceElements =  httpResponse.getDocument().select("p[id=userId]");
        element1 = priceElements.get(0);
        String userId = element1.text();
        logger.info("userId:"+userId);

        priceElements =  httpResponse.getDocument().select("p[id=sign]");
        element1 = priceElements.get(0);
        String sign = element1.text();

        priceElements =  httpResponse.getDocument().select("p[id=mchName]");
        element1 = priceElements.get(0);
        String mchName = element1.text();
        logger.info("mchName:"+mchName);
        priceElements =  httpResponse.getDocument().select("p[id=outTradeNo]");
        element1 = priceElements.get(0);
        String outTradeNo = element1.text();
        priceElements =  httpResponse.getDocument().select("p[id=body]");
        element1 = priceElements.get(0);
        String body = element1.text();
        logger.info("body:"+body);

        priceElements =  httpResponse.getDocument().select("p[id=client]");
        element1 = priceElements.get(0);
        String client = element1.text();
        logger.info("client:"+client);

        priceElements =  httpResponse.getDocument().select("p[id=userName]");
        element1 = priceElements.get(0);
        String userName = element1.text();
        priceElements =  httpResponse.getDocument().select("p[id=payType]");
        element1 = priceElements.get(0);
        String payType = element1.text();
        priceElements =  httpResponse.getDocument().select("p[id=openID]");
        element1 = priceElements.get(0);
        String openID = element1.text();
        logger.info("openID:"+openID);

        priceElements =  httpResponse.getDocument().select("p[id=subOpenID]");
        element1 = priceElements.get(0);
        String subOpenID = element1.text();
        priceElements =  httpResponse.getDocument().select("p[id=pierce]");
        element1 = priceElements.get(0);
        String pierce = element1.text();
        logger.info("pierce:"+pierce);

        priceElements =  httpResponse.getDocument().select("p[id=appId]");
        element1 = priceElements.get(0);
        String appId = element1.text();
        dataMap = new HashMap();
        dataMap.put("mchId",mchId);
        dataMap.put("userId","");
        dataMap.put("mchName",mchName);
        dataMap.put("outTradeNo","");
        dataMap.put("body",body);
        dataMap.put("client",client);
        dataMap.put("userName","");
        dataMap.put("payType","");
        dataMap.put("openID",openID);
        dataMap.put("subOpenID","");
        dataMap.put("appId","");
        dataMap.put("attach","");
        dataMap.put("pierce",pierce);
        dataMap.put("openid",orderInfo.getAliUserId());
        dataMap.put("type","2");
        dataMap.put("qrCodeId",cookieObj.getString("qrCodeId"));
        dataMap.put("latitude",ipObject.getString("latitude"));
        dataMap.put("longitude",ipObject.getString("longitude"));
        dataMap.put("amount",orderInfo.getMoney()+"");
        dataMap.put("appid","wxa4410d796464c93d");

        url = "https://api.haoduo.fun/pay/scanPay/realPay";
        logger.info("下单URL："+url);
        StringBuilder buf = new StringBuilder("");
        HttpUtils.buildPayParams(buf, dataMap);
        String preStr = buf.toString();
        logger.info("请求参数："+preStr);

//        headerMap.put("Referer","https://www.shouyinbei.net/wap/merchant/h5pay?auth_code="+orderInfo.getAliAuthCode()+"&userAppId="+qrcode_);

        String payHttpResponse = HttpUtils.sendPostRequest(url,preStr,headerMap);

        logger.info("hdf请求返回的:"+payHttpResponse);

        JSONObject payInforesultObj = JSONObject.parseObject(payHttpResponse);
        if(payInforesultObj.getIntValue("code")!=200){
            jsonObject.put("code","100");
            jsonObject.put("msg","获取连接失败");
            return jsonObject;
        }
        JSONObject jspay_info = payInforesultObj.getJSONObject("data");
//        JSONObject payInfoObj = new JSONObject();
//        payInfoObj.put("appid",payInforesultObj.getString("appid"));
//        payInfoObj.put("merchant_id",payInforesultObj.getString("merchant_id"));
//        payInfoObj.put("qrcode",qrcode_);
//        payInfoObj.put("order_id",payInforesultObj.getString("order_id"));
//        payInfoObj.put("notify_key",payInforesultObj.getString("notify_key"));
//        payInfoObj.put("third_order_id",payInforesultObj.getString("third_order_id"));
//        orderInfo.setQrcodeTxt(payInfoObj.toJSONString());
//        orderInfoDao.update(orderInfo);
        jsonObject.put("payUrl",jspay_info.toJSONString());
        jsonObject.put("orderNo",jspay_info.getString("orderNo"));
        jsonObject.put("code","200");
        return jsonObject;
    }


    @Override
    public ResponseData smartReissueOrder(TOrderInfo orderInfo) throws Exception {
        return new ResponseData();
    }
}
